/** *******************************************************************
 * FlexDatabaseManager
 * @author  Jonnie Spratley
 * @contact jonniespratley@gmail.com
 * @internal
 ******************************************************************* */
package com.jonniespratley.flexdatabasemanager.commands.tables
{
	import com.adobe.cairngorm.commands.ICommand;
	import com.adobe.cairngorm.control.CairngormEvent;
	import com.jonniespratley.flexdatabasemanager.business.FlexDatabaseManagerDelegate;
	import com.jonniespratley.flexdatabasemanager.events.tables.RemoveTableEvent;
	import com.jonniespratley.flexdatabasemanager.model.ModelLocator;
	import com.jonniespratley.flexdatabasemanager.vo.*;
	
	import mx.controls.Alert;
	import mx.rpc.IResponder;
	import mx.rpc.events.FaultEvent;
	import mx.rpc.events.ResultEvent;

	public class RemoveTableCommand implements ICommand, IResponder
	{
		private var model:ModelLocator = ModelLocator.getInstance();

		public function execute( event:CairngormEvent ) : void
		{
			model.interactingWithServer = true;
				
			var evt:RemoveTableEvent = event as RemoveTableEvent;
			var delegate:FlexDatabaseManagerDelegate  = new FlexDatabaseManagerDelegate( this );
			
			if ( model.selectedDatabase == null && model.selectedTable == null )
			{
				Alert.show( 'Please select a database and/or table before removing.' );
				return;
			} else {
				delegate.removeTable( model.currentUser, model.selectedDatabase, model.selectedTable );
			}

		}

		public function result( data:Object ) : void
		{
			model.interactingWithServer = false;
			
			var result:ResultEvent = data as ResultEvent;
			
			if ( data.result == 1 )
			{
				Alert.show( result.token.table.tableName + ' was removed.', 'Alert' );
			}
			
			
			trace( data.result );
		}

		public function fault( fault:Object ):void
		{
			model.interactingWithServer = false;
			
			var faultEvt:FaultEvent = fault as FaultEvent;
			Alert.show(faultEvt.fault.toString(), "Error");
			trace(faultEvt.fault.faultString);
		}

	}
}